package com.teragadgets.android.comics.appengine;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class WebComic {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;

	@Persistent
	private String favicon;

	@Persistent
	private String name;

	@Persistent
	private String url;

	@Persistent
	private int latestComic = 0;

	@Persistent
	private String latestComicURL;

	@Persistent
	private String nextButtonRegex;

	@Persistent
	private String comicNameRegex;

	@Persistent
	private String comicImageRegex;

	@Persistent
	private String comicAltTextRegex;

	public WebComic(String name, String url, String favicon) {
		this.name = name;
		this.url = url;
		this.favicon = favicon;
	}

	public void setNextButtonRegex(String regex) {
		this.nextButtonRegex = regex;
	}

	public void setComicNameRegex(String regex) {
		this.comicNameRegex = regex;
	}

	public void setComicImageRegex(String regex) {
		this.comicImageRegex = regex;
	}

	public void setComicAltTextRegex(String regex) {
		this.comicAltTextRegex = regex;
	}

	public void setLatestComic(String url) {
		this.latestComic++;
		this.latestComicURL = url;
	}

	public String getFavicon() {
		return favicon;
	}

	public String getName() {
		return escapeXML(name);
	}

	public int getLatestComic() {
		return latestComic;
	}

	public String getLatestComicURL() {
		return url + latestComicURL;
	}

	public Long getID() {
		return id;
	}

	public String getNextButtonRegex() {
		return nextButtonRegex;
	}

	public String getComicNameRegex() {
		return comicNameRegex;
	}

	public String getComicImageRegex() {
		return comicImageRegex;
	}

	public String getComicAltTextRegex() {
		return comicAltTextRegex;
	}

	public String getURL() {
		return url;
	}

	public static String escapeXML(String s) {
		StringBuilder result = new StringBuilder();
		StringCharacterIterator i = new StringCharacterIterator(s);
		char c = i.current();
		while (c != CharacterIterator.DONE) {
			switch (c) {
			case '"':
				result.append("&quot;");
				break;
			case '\'':
				result.append("&#39;");
				break;
			case '&':
				result.append("&amp;");
				break;
			default:
				result.append(c);
			}
			c = i.next();
		}
		return result.toString();
	}

	public void decreaseComicCount() {
		latestComic--;
	}
}